package com.mgvlife.ddlw.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import com.mgvlife.ddlw.dao.DaoSupportExtra;
import com.mgvlife.ddlw.entity.Admin;
import com.mgvlife.ddlw.entity.Clazz;
import com.mgvlife.ddlw.entity.Course;
import com.mgvlife.ddlw.entity.Schedule;
import com.mgvlife.ddlw.entity.SignInFile;
import com.mgvlife.ddlw.entity.SignInInfo;
import com.mgvlife.ddlw.entity.Student;
import com.mgvlife.ddlw.formbean.ScheduleForm;
import com.mgvlife.ddlw.service.ScheduleService;
import com.mgvlife.ddlw.util.ExcelUtils;
import com.mgvlife.ddlw.util.HttpSessionUtil;
import com.mgvlife.ddlw.vo.Result;
import com.mgvlife.ddlw.vo.VoClazz2;
import com.mgvlife.ddlw.vo.VoSchedule;
import com.xinhuo.exception.DaoException;
import com.xinhuo.util.DateUtil;
import com.xinhuo.util.FileUtil;
import com.xinhuo.util.QueryResult;
import com.xinhuo.vo.JsonEasyUI;

@Service("scheduleService")
public class ScheduleServiceImpl extends DaoSupportExtra implements
		ScheduleService {

	public Result scheduleAdd(ScheduleForm dataForm) throws Exception {
		String adminId = HttpSessionUtil.getAdminStatus();
		Admin admin = this.findById(Admin.class, adminId);
		if (admin == null) {
			return new Result("error", "请先登陆");
		}
		Course course = this.findById(Course.class, dataForm.getCourseId());
		if (course == null) {
			return new Result("error", "无此课程");
		}
		// 获取班级信息
		String[] clazzs = dataForm.getClazzs();
		List<Clazz> clazz_l = null;
		String whereSQL;
		Object[] whereParams;
		if (clazzs != null) {
			boolean isFirst = true;
			whereSQL = "";
			whereParams = new Object[clazzs.length];
			for (int i = 0; i < clazzs.length; i++) {
				if (isFirst) {
					whereSQL += " id=?";
					whereParams[i] = clazzs[i];
					isFirst = false;
				} else {
					whereSQL += " or id=?";
					whereParams[i] = clazzs[i];
				}
			}
			clazz_l = this.findAll(Clazz.class, whereSQL, whereParams);
		} else {
			clazz_l = new ArrayList<Clazz>();
		}
		Schedule schedule = new Schedule();
		for (Clazz clazz : clazz_l) {
			clazz.getSchedules().add(schedule);
		}
		course.getSchedules().add(schedule);
		schedule.setId(UUID.randomUUID().toString());
		schedule.setCourse(course);
		schedule.setClazzs(clazz_l);
		schedule.setSignInInfos(new ArrayList<SignInInfo>());
		schedule.setClazzTime(DateUtil.dataToString(new Date()));
		schedule.setStatus(0);
		schedule.setAdmin(admin);
		SignInFile signInFile = new SignInFile();
		signInFile.setId(UUID.randomUUID().toString());
		signInFile.setFileName("");
		schedule.setSignInFile(signInFile);
		this.save(schedule);
		return Result.success();
	}

	public Result scheduleUpdate(ScheduleForm dataForm) throws Exception {
		return new Result("error", "抱歉,暂不提供此功能");
	}

	public Result scheduleDelete(ScheduleForm dataForm) throws Exception {
		String filePath = ServletActionContext.getServletContext().getRealPath(
				"/data/");
		String idstr = dataForm.getId();
		if (idstr != null && idstr.length() > 0) {
			String whereSQL = "";
			String[] ids = idstr.split(";");
			boolean isFirst = true;
			for (int i = 0; i < ids.length; i++) {
				if (isFirst) {
					whereSQL = "id=?";
					isFirst = false;
				} else {
					whereSQL += " or id=?";
				}
			}
			List<Schedule> schedules = this.findAll(Schedule.class, whereSQL,
					ids);
			for (Schedule schedule : schedules) {
				schedule.setAdmin(null);
				for (Clazz clazz : schedule.getClazzs()) {
					clazz.getSchedules().remove(schedule);
					for (SignInInfo signInInfo : schedule.getSignInInfos()) {
						signInInfo.getStudent().getSignInInfos()
								.remove(signInInfo);
					}
				}
				schedule.getCourse().getSchedules().remove(schedule);
				FileUtil.deleteFile(filePath + "\\" + schedule.getSignInFile().getFileName());
				this.delete(schedule);
			}
		} else {
			return new Result("error", "课次不存在");
		}
		return Result.success();
	}

	public JsonEasyUI<VoSchedule> getData(ScheduleForm dataForm)
			throws DaoException {
		JsonEasyUI<VoSchedule> result = new JsonEasyUI<VoSchedule>();
		QueryResult<Schedule> qr = null;
		if (dataForm.getSearchTitle() == null ? false : dataForm
				.getSearchTitle().equals("clazzTime")) {
			String whereSQL = "clazzTime>=? and clazzTime<=?";
			Date date1 = DateUtil.formatSQL(dataForm.getSearch());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date1);
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			date1 = calendar.getTime();
			Object[] whereParams = { DateUtil.formatSQL(dataForm.getSearch()),
					date1 };
			qr = this.getScrollData(Schedule.class, whereSQL, whereParams,
					null, null, dataForm.getPage(), dataForm.getRows(),
					dataForm.getSort(), dataForm.getOrder());
		} else {
			qr = this.getScrollData(Schedule.class, null, null,
					dataForm.getSearchTitle(), dataForm.getSearch(),
					dataForm.getPage(), dataForm.getRows(), dataForm.getSort(),
					dataForm.getOrder());
		}
		result.setTotal(qr.getTotalrecord());
		List<VoSchedule> sche_l = new ArrayList<VoSchedule>();
		for (Schedule schedule : qr.getResultList()) {
			sche_l.add(new VoSchedule(schedule));
		}
		result.setRows(sche_l);
		return result;
	}

	public JsonEasyUI<VoSchedule> getDataByAdmin(ScheduleForm dataForm)
			throws DaoException {
		JsonEasyUI<VoSchedule> result = new JsonEasyUI<VoSchedule>();
		QueryResult<Schedule> qr = null;
		if (dataForm.getSearchTitle() == null ? false : dataForm
				.getSearchTitle().equals("clazzTime")) {
			String whereSQL = "clazzTime>=? and clazzTime<=? and admin=?";
			Date date1 = DateUtil.formatSQL(dataForm.getSearch());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date1);
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			date1 = calendar.getTime();
			String adminId = HttpSessionUtil.getAdminStatus();
			Admin admin = this.findById(Admin.class, adminId);
			if (admin == null) {
				return null;
			}
			Object[] whereParams = { DateUtil.formatSQL(dataForm.getSearch()),
					date1, admin };
			qr = this.getScrollData(Schedule.class, whereSQL, whereParams,
					null, null, dataForm.getPage(), dataForm.getRows(),
					dataForm.getSort(), dataForm.getOrder());
		} else {
			String adminId = HttpSessionUtil.getAdminStatus();
			Admin admin = this.findById(Admin.class, adminId);
			if (admin == null) {
				return null;
			}
			String whereSQL1 = "admin=?";
			Object[] whereParams1 = { admin };
			qr = this.getScrollData(Schedule.class, whereSQL1, whereParams1,
					dataForm.getSearchTitle(), dataForm.getSearch(),
					dataForm.getPage(), dataForm.getRows(), dataForm.getSort(),
					dataForm.getOrder());
		}
		result.setTotal(qr.getTotalrecord());
		List<VoSchedule> sche_l = new ArrayList<VoSchedule>();
		for (Schedule schedule : qr.getResultList()) {
			sche_l.add(new VoSchedule(schedule));
		}
		result.setRows(sche_l);
		return result;
	}

	public JsonEasyUI<VoClazz2> getClazzsData(ScheduleForm dataForm)
			throws Exception {
		JsonEasyUI<VoClazz2> result = new JsonEasyUI<VoClazz2>();
		Schedule schedule = this.findById(Schedule.class, dataForm.getId());
		if (schedule == null) {
			return null;
		}
		List<VoClazz2> clazz_l = new ArrayList<VoClazz2>();
		for (Clazz clazz : schedule.getClazzs()) {
			clazz_l.add(new VoClazz2(clazz));
		}
		result.setRows(clazz_l);
		result.setTotal((long) clazz_l.size());
		return result;
	}

	public Result startDd(ScheduleForm dataForm) throws Exception {
		String scheId = dataForm.getId();
		Schedule schedule = this.findById(Schedule.class, scheId);
		if (schedule == null) {
			return new Result("error", "没有此课次");
		}
		if (schedule.getStatus() == 1) {
			return Result.success();
		}
		for (Clazz clazz : schedule.getClazzs()) {
			for (Student student : clazz.getStudents()) {
				SignInInfo signInInfo = new SignInInfo();
				signInInfo.setId(UUID.randomUUID().toString());
				signInInfo.setStudent(student);
				signInInfo.setSchedule(schedule);
				signInInfo.setSignInTime(null);
				signInInfo.setSignInStatus(-1);
				this.save(signInInfo);
				schedule.getSignInInfos().add(signInInfo);
				student.getSignInInfos().add(signInInfo);
			}
		}
		schedule.setStatus(1);
		this.update(schedule);
		return Result.success();
	}

	public Result downLoadExcel(ScheduleForm dataForm) throws IOException {
		String fileName = "签到信息";
		HttpServletResponse response = ServletActionContext.getResponse();
		String filePath = ServletActionContext.getServletContext().getRealPath(
				"/data/");
		String scheduleId = dataForm.getId();
		Schedule schedule = this.findById(Schedule.class, scheduleId);
		if (schedule == null) {
			return new Result("error", "无此课次");
		}
		String adminId = HttpSessionUtil.getAdminStatus();
		Admin admin = null;
		if (adminId != null && !adminId.trim().equals("")) {
			admin = this.findById(Admin.class, adminId);
			if (admin == null) {
				return new Result("error", "登陆超时");
			}
		}
		File file = null;
		if (schedule.getStatus() == 1) {
			SignInFile signInFile = schedule.getSignInFile();
			String fileName2 = signInFile.getFileName();
			if (fileName2 != null && !fileName2.trim().equals("")) {
				FileUtil.deleteFile(filePath + "\\" + fileName2);
			}
			// 创建文件
			file = ExcelUtils.writeExcel(filePath, fileName, "签到", schedule);
			FileUtil.saveFile(file, new File(filePath + fileName));
			signInFile.setFileName(file.getName());
			FileUtil.downLoadFile(response, "/data/", file.getName());
			this.update(signInFile);
		} else {
			return new Result("error", "尚未开始点到！");
		}
		return new Result("success", "下载成功");
	}

	// 通过时间去判断
	private boolean checkScheduleExist(String clazzTime) throws DaoException {
		return this.getScheCount(clazzTime);
	}

}
